package com.bys.admin.system.service.impl;

import com.bys.security.context.AuthenticationContextHolder;
import com.bys.admin.system.dto.LoginUser;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginService {

    @Resource
    private TokenService tokenService;
    @Resource
    private AuthenticationManager authenticationManager;
    public Map<String,Object> login(String username, String password) {
        Map<String, Object> map = new HashMap<>();
        // 用户验证
        Authentication authentication = null;
        loginPreCheck(username,password);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
        try {
//            将账号密码存入全局中
            AuthenticationContextHolder.setContext(authenticationToken);
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            AuthenticationContextHolder.clearContext();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//        记录用户登录信息
        recordLoginInfo(loginUser.getId());
        String token = tokenService.createToken(loginUser);
        map.put("token",token);
        map.put("userInfo", loginUser.getUser());
        // 生成token
        return  map;
    }

    /**
     * 记录用户登录信息
     * @param id  用户Id
     */
    private void recordLoginInfo(Long id) {

    }

    /**
     * 登录前校验
     */
    private void loginPreCheck(String username, String password) {

            // IP黑名单校验

    }
}
